package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// 获取请求的body内容并转换为字符串
func getRequestBody(ctx *gin.Context) any {
	body, err := io.ReadAll(ctx.Request.Body)
	if err != nil {
		return gin.H{
			"error":   "Error reading request body",
			"details": err.Error(),
			"raw":     "",
		}
	}

	// 重新将body放回到请求中，以便后续可能的读取
	ctx.Request.Body = io.NopCloser(strings.NewReader(string(body)))

	// 尝试解析为JSON
	var jsonBody any
	if err := json.Unmarshal(body, &jsonBody); err != nil {
		// 解析失败，返回原始字符串
		return map[string]string{}
	}

	// 解析成功，返回结构化的JSON
	return jsonBody
}

// 获取URL查询参数
func getQueryParams(ctx *gin.Context) map[string]string {
	params := make(map[string]string)
	for key, values := range ctx.Request.URL.Query() {
		if len(values) > 0 {
			params[key] = values[0]
		}
	}
	return params
}

// 获取表单数据
func getFormData(ctx *gin.Context) map[string]string {
	formData := make(map[string]string)

	// 解析表单数据
	if err := ctx.Request.ParseForm(); err != nil {
		formData["error"] = "Error parsing form data: " + err.Error()
		return formData
	}

	for key, values := range ctx.Request.PostForm {
		if len(values) > 0 {
			formData[key] = values[0]
		}
	}
	return formData
}

// 获取Cookies
func getCookies(ctx *gin.Context) map[string]string {
	cookies := make(map[string]string)
	for _, cookie := range ctx.Request.Cookies() {
		cookies[cookie.Name] = cookie.Value
	}
	return cookies
}

// 通用处理函数，处理所有HTTP方法的请求
func handleRequest(ctx *gin.Context) {
	// 获取各种请求信息
	requestInfo := gin.H{
		"method":           ctx.Request.Method,
		"path":             ctx.Request.URL.Path,
		"host":             ctx.Request.Host,
		"requestURI":       ctx.Request.RequestURI,
		"url":              ctx.Request.URL.String(),
		"fullURL":          ctx.Request.Host + ctx.Request.URL.String(),
		"protocol":         ctx.Request.Proto,
		"remoteAddr":       ctx.Request.RemoteAddr,
		"clientIP":         ctx.ClientIP(),
		"remoteIP":         ctx.RemoteIP(),
		"userAgent":        ctx.Request.UserAgent(),
		"referer":          ctx.Request.Referer(),
		"contentLength":    ctx.Request.ContentLength,
		"contentType":      ctx.ContentType(),
		"transferEncoding": ctx.Request.TransferEncoding,
		"headers":          ctx.Request.Header,
		"queryParams":      getQueryParams(ctx),
		"formData":         getFormData(ctx),
		"cookies":          getCookies(ctx),
		"body":             getRequestBody(ctx),
	}

	// gin.H 转换成 JSON字符串
	requestInfoJSON, _ := json.Marshal(requestInfo)
	fmt.Println("requestInfo:", string(requestInfoJSON))

	// 返回所有收集到的信息
	ctx.JSON(http.StatusOK, requestInfo)
}

func main() {
	gin.SetMode(gin.ReleaseMode)

	// 创建Gin引擎
	app := gin.Default()

	// 为所有常用HTTP方法注册相同的处理函数，路径都是"/"
	app.GET("/", handleRequest)
	app.POST("/", handleRequest)
	app.PUT("/", handleRequest)
	app.PATCH("/", handleRequest)
	app.DELETE("/", handleRequest)
	app.OPTIONS("/", handleRequest)
	app.HEAD("/", handleRequest)

	// 启动服务器，监听8056端口
	if err := app.Run(":8056"); err != nil {
		panic("Failed to start server: " + err.Error())
	}
}
